from flask import Blueprint, jsonify, request
from app.services.msg_service import MsgService

def init_msg_routes(socketio):
    msg_bp = Blueprint('msg', __name__)
    msg_service = MsgService(socketio)
    
    # 注意这里的路由路径已经包含了/api/msg前缀
    @msg_bp.route('/realtime', methods=['POST'])  # 完整路径: /api/msg/realtime
    def receive_realtime_data():
        """接收实时数据"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({"code": 400, "message": "无效数据"}), 400
            
            result = msg_service.process_realtime_data(data)
            return jsonify(result), 200
            
        except Exception as e:
            return jsonify({
                "code": 500, 
                "message": f"处理实时数据时出错: {str(e)}"
            }), 500

    @msg_bp.route('/status', methods=['POST'])  # 完整路径: /api/msg/status
    def receive_status_data():
        """接收状态数据"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({"code": 400, "message": "无效数据"}), 400
            
            result = msg_service.process_status_data(data)
            return jsonify(result), 200
            
        except Exception as e:
            return jsonify({
                "code": 500, 
                "message": f"处理状态数据时出错: {str(e)}"
            }), 500

    @msg_bp.route('/event', methods=['POST'])  # 完整路径: /api/msg/event
    def receive_event_data():
        """接收事件数据"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({"code": 400, "message": "无效数据"}), 400
            
            result = msg_service.process_event_data(data)
            return jsonify(result), 200
            
        except Exception as e:
            return jsonify({
                "code": 500, 
                "message": f"处理事件数据时出错: {str(e)}"
            }), 500


    return msg_bp